package com.lw.leetcode.str.a;

/**
 * Created with IntelliJ IDEA.
 * str
 * 859. 亲密字符串
 *
 * @author liw
 * @version 1.0
 * @date 2021/9/30 14:08
 */
public class BuddyStrings {

    public boolean buddyStrings(String A, String B) {
        if (A.length() != B.length()) {
            return false;
        }
        if (A.equals(B)) {
            for (int i = 0; i < A.length(); i++) {
                if (A.indexOf(A.charAt(i)) != i) {
                    return true;
                }
            }
            return false;
        }
        int count = 0;
        char strA1 = 0, strA2 = 0, strB1 = 0, strB2 = 0;
        for (int i = 0; i < A.length(); i++) {
            if (A.charAt(i) != B.charAt(i)) {
                count++;
                if (count == 1) {
                    strA1 = A.charAt(i);
                    strB1 = B.charAt(i);
                }
                if (count == 2) {
                    strA2 = A.charAt(i);
                    strB2 = B.charAt(i);
                }
            }
            if (count > 2) {
                return false;
            }
        }
        return count == 2 && strA1 == strB2 && strA2 == strB1;
    }

}
